package com.zjk.wrench.design.framework.tree;

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public abstract class AbstractMultiThreadStrategyRouter<T, D, R> implements StrategyMapper<T, D, R>, StrategyHandler<T, D, R> {

    protected StrategyHandler<T, D, R> defaultStrategyHandler = StrategyHandler.DEFAULT;

    /**
     * 路由
     * @param requestParameters 入参
     * @param dynamicContext 上下文
     * @return 策略执行结果
     * @throws Exception
     */
    public R router(T requestParameters, D dynamicContext) throws Exception{
        StrategyHandler<T, D, R> strategyHandler = getStrategy(requestParameters, dynamicContext);
        if(strategyHandler == null){
            strategyHandler = defaultStrategyHandler;
        }
        return strategyHandler.apply(requestParameters, dynamicContext);
    }

    @Override
    public R apply(T requestParameters, D dynamicContext) throws Exception {
        // 异步加载数据
        multiThread(requestParameters, dynamicContext);
        // 业务流程受理
        return doApply(requestParameters, dynamicContext);

    }

    protected abstract R doApply(T requestParameters, D dynamicContext) throws Exception;

    protected abstract void multiThread(T requestParameters, D dynamicContext);
}
